package com.yang.service.wximpl;

import com.yang.bean.*;
import com.yang.bean.bj.vo.CartTotal;
import com.yang.bean.bj.vo.CartVO;
import com.yang.bean.bj.vo.CheckOutVO;
import com.yang.bean.bj.vo.ProductIdVO;
import com.yang.mapper.*;
import com.yang.service.wx.CartServiceWX;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description: TOOD
 * @return:
 * @author: BaoZi
 * @date: 2022/9/9
 */
@Service
public class CartServiceWXImpl implements CartServiceWX {

    @Autowired
    CartMapper cartMapper;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketOrderMapper marketOrderMapper;
    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Override
    public CartVO queryCart(Integer userId) {
        CartVO cartVO = new CartVO();
        CartTotal cartTotal = new CartTotal();
        cartTotal.setCheckedGoodsCount(0);
        cartTotal.setGoodsCount(0);
        cartTotal.setCheckedGoodsAmount(new BigDecimal(0));
        cartTotal.setGoodsAmount(new BigDecimal(0));
        cartVO.setCartTotal(cartTotal);
        cartVO.setCartList(new ArrayList<MarketCart>());
        //根据userId查出购物车中没有逻辑删除的商品
        MarketCartExample cartExample1 = new MarketCartExample();
        MarketCartExample.Criteria criteria2 = cartExample1.createCriteria();
        criteria2.andUserIdEqualTo(userId);
        criteria2.andDeletedEqualTo(false);
        List<MarketCart> marketCarts1 = marketCartMapper.selectByExample(cartExample1);
        //购物车非空
        if (marketCarts1.size()!=0) {
            //购车商品总数和总金额
            BigDecimal goodsAmount = BigDecimal.ZERO;
            Integer goodsCount = 0;
            for (MarketCart cart1 : marketCarts1) {
                BigDecimal price = ((cart1.getPrice()).multiply(new BigDecimal(cart1.getNumber())));
                goodsAmount = goodsAmount.add(price);
                goodsCount += cart1.getNumber();
            }
            cartTotal.setGoodsCount(goodsCount);
            cartTotal.setGoodsAmount(goodsAmount);

            //查出购车中被选中的商品总数和总金额
            MarketCartExample cartExample2 = new MarketCartExample();
            MarketCartExample.Criteria criteria3 = cartExample1.createCriteria();
            criteria3.andUserIdEqualTo(userId);
            criteria3.andDeletedEqualTo(false);//未删除
            criteria3.andCheckedEqualTo(true);//被选中
            List<MarketCart> marketCarts2 = marketCartMapper.selectByExample(cartExample2);
            BigDecimal goodsAmount1 = BigDecimal.ZERO;
            Integer goodsCount1 = 0;
            for (MarketCart cart2 : marketCarts2) {
                BigDecimal price1 = ((cart2.getPrice()).multiply(new BigDecimal(cart2.getNumber())));
                goodsAmount1 = goodsAmount1.add(price1);
                goodsCount1 += cart2.getNumber();
            }
            cartTotal.setCheckedGoodsCount(goodsCount1);
            cartTotal.setCheckedGoodsAmount(goodsAmount1);

            cartVO.setCartList(marketCarts1);
            cartVO.setCartTotal(cartTotal);
        }
        //购物车空
        return cartVO;
    }


    @Override
    public Integer insertCart(MarketCart marketCart,Integer userId) {
        Integer cartCount = 0;
        //查询购物车中有无此商品
        //先根据userId,GoodsId,ProductId 查出cart表的信息
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andGoodsIdEqualTo(marketCart.getGoodsId());
        criteria.andProductIdEqualTo(marketCart.getProductId());
        criteria.andDeletedEqualTo(false);
        List <MarketCart> cartList = marketCartMapper.selectByExample(cartExample);
        if (cartList.size()!=0){
            //购物车已有要添加的商品，修改数量即可
            for (MarketCart cart : cartList) {
                MarketCartExample cartExample1 = new MarketCartExample();
                MarketCartExample.Criteria criteria1 = cartExample1.createCriteria();
                criteria1.andIdEqualTo(cart.getId());
                MarketCart marketCart1 = new MarketCart();
                marketCart1.setNumber(marketCart.getNumber()+ cart.getNumber());
                marketCartMapper.updateByExampleSelective(marketCart1, cartExample1);
                Integer count = queryCountCart(cart.getUserId());
                cartCount = count;
            }
        }else {
            //购物车没有要添加的商品，新添加
            //根据goodsId查询goods表,
            MarketGoodsExample goodsExample = new MarketGoodsExample();
            MarketGoodsExample.Criteria criteria2 = goodsExample.createCriteria();
            criteria2.andIdEqualTo(marketCart.getGoodsId());
            List<MarketGoods> goodsList = goodsMapper.selectByExample(goodsExample);
            for (MarketGoods goods : goodsList) {
                marketCart.setGoodsSn(goods.getGoodsSn());
                marketCart.setGoodsName(goods.getName());
            }

            //根据productId查询product表
            MarketGoodsProductExample goodsProductExample = new MarketGoodsProductExample();
            MarketGoodsProductExample.Criteria criteria3 = goodsProductExample.createCriteria();
            criteria3.andIdEqualTo(marketCart.getProductId());
            List<MarketGoodsProduct> goodsProducts = marketGoodsProductMapper.selectByExample(goodsProductExample);
            for (MarketGoodsProduct goodsProduct : goodsProducts) {
                marketCart.setPrice(goodsProduct.getPrice());
                marketCart.setSpecifications(goodsProduct.getSpecifications());
                marketCart.setPicUrl(goodsProduct.getUrl());
                marketCart.setDeleted(false);//未删除
            }
            marketCart.setAddTime(new Date());
            marketCart.setUpdateTime(new Date());
            marketCart.setUserId(userId);
            //刚添加是选中状态
            marketCart.setChecked(true);
            //将商品信息插入到购物车表中
            marketCartMapper.insert(marketCart);
            //返回购物车商品数量
            Integer count = queryCountCart(userId);
            cartCount = count;
        }
        return cartCount;
    }


    @Override
    public Integer addCart(MarketCart marketCart, Integer userId) {

        Integer cartId = 0;//需要返回的cartId
        //先根据userId,GoodsId,ProductId 查出cart表的信息
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andGoodsIdEqualTo(marketCart.getGoodsId());
        criteria.andProductIdEqualTo(marketCart.getProductId());
        criteria.andDeletedEqualTo(false);
        List <MarketCart> cartList = marketCartMapper.selectByExample(cartExample);

        //如果list不为空则说明购物车已经有对应的商品
        if (cartList.size()!=0) {
            for (MarketCart cart : cartList) {
                //覆盖原来信息
                MarketCartExample cartExample1 = new MarketCartExample();
                MarketCartExample.Criteria criteria2 = cartExample1.createCriteria();
                criteria2.andIdEqualTo(cart.getId());
                MarketCart marketCart1 = new MarketCart();
                marketCart1.setNumber(marketCart.getNumber());
                marketCart1.setPrice((cart.getPrice()).multiply(new BigDecimal(marketCart.getNumber())));
                marketCartMapper.updateByExampleSelective(marketCart1, cartExample1);
                cartId = cart.getId();//返回原来的id
            }
        } else {
            //为空，新添商品
            //根据goodsId查询goods表,
            MarketGoodsExample goodsExample = new MarketGoodsExample();
            MarketGoodsExample.Criteria criteria3 = goodsExample.createCriteria();
            criteria3.andIdEqualTo( marketCart.getGoodsId());
            List<MarketGoods> goodsList = goodsMapper.selectByExample(goodsExample);
            for (MarketGoods goods : goodsList) {
                marketCart.setGoodsSn(goods.getGoodsSn());
                marketCart.setGoodsName(goods.getName());
            }

            //根据productId查询product表
            MarketGoodsProductExample goodsProductExample = new MarketGoodsProductExample();
            MarketGoodsProductExample.Criteria criteria1 = goodsProductExample.createCriteria();
            criteria1.andIdEqualTo(marketCart.getProductId());
            List<MarketGoodsProduct> goodsProducts = marketGoodsProductMapper.selectByExample(goodsProductExample);
            for (MarketGoodsProduct goodsProduct : goodsProducts) {
                marketCart.setPrice((goodsProduct.getPrice()).multiply(new BigDecimal(marketCart.getNumber())));
                marketCart.setSpecifications(goodsProduct.getSpecifications());
                marketCart.setPicUrl(goodsProduct.getUrl());
                marketCart.setDeleted(false);//未删除
            }
            marketCart.setAddTime(new Date());
            marketCart.setUpdateTime(new Date());
            //刚添加是选中状态
            marketCart.setChecked(true);
            //将商品信息插入到购物车表中
            int insert = marketCartMapper.insert(marketCart);
            cartId = insert;
        }
        return cartId;
    }

    @Override
    public Integer queryCountCart(Integer userId) {
        Integer sum = 0;
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(cartExample);
        if (marketCarts.size()!=0){
            for (MarketCart cart : marketCarts) {
                cart.getNumber();
                sum += cart.getNumber();
            }
        }
        return sum;
    }

    @Override
    public void updateCartById(MarketCart marketCart) {

            MarketCartExample cartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = cartExample.createCriteria();
            MarketCart marketCart1 = new MarketCart();
            //修改商品数量
            marketCart1.setNumber(marketCart.getNumber());
            criteria.andIdEqualTo(marketCart.getId());
            marketCartMapper.updateByExampleSelective(marketCart1,cartExample);

    }

    @Override
    public CartVO deleteCartById(ProductIdVO productIdVO, Integer userId) {
        //根据productId删除商品
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andProductIdIn(productIdVO.getProductIds());
        marketCartMapper.deleteByExample(cartExample);
        CartVO cartVO = queryCart(userId);
        return cartVO;
    }

    @Override
    public CartVO checkedGoods(ProductIdVO productIdVO,Integer userId) {
        //修改check为请求参数中的checkId
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andProductIdIn(productIdVO.getProductIds());
        MarketCart marketCart = new MarketCart();
        if (productIdVO.getIsChecked()==0){
            marketCart.setChecked(false);
        }else {
            marketCart.setChecked(true);
        }
        criteria.andProductIdIn(productIdVO.getProductIds());
        criteria.andUserIdEqualTo(userId);
        marketCartMapper.updateByExampleSelective(marketCart,cartExample);
        CartVO cartVO = queryCart(userId);
        return cartVO;
    }

    @Override
    public CheckOutVO queryCheckOut(CheckOutVO checkOut) {

        //查system表
//        MarketSystemExample example = new MarketSystemExample();
////        MarketSystemExample.Criteria criteria3 = example.createCriteria();
////        criteria3.andKeyNameEqualTo("market_express_freight_min");
////        criteria3.andKeyNameEqualTo("market_express_freight_value");
////        List<MarketSystem> list = marketSystemMapper.selectByExample(example);
////
////        MarketOrder marketOrder = new MarketOrder();
////        for (MarketSystem system : list) {
////            if (system.getKeyName().equals("market_express_freight_min")){
////                marketOrder.setActualPrice(new BigDecimal(system.getKeyValue()));//满减金额
////            }
////            marketOrder.setFreightPrice(new BigDecimal(system.getKeyValue()));//运费
////        }

        //查address表
        MarketAddress allAddress = marketAddressMapper.selectByPrimaryKey(checkOut.getAddressId());
        checkOut.setCheckedAddress(allAddress);

        //查Cart表
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andIdEqualTo(checkOut.getCartId());
        List <MarketCart> marketCart = marketCartMapper.selectByExample(cartExample);
        checkOut.setCheckedGoodsList(marketCart);


        //根据userId查order表
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria1 = orderExample.createCriteria();
        criteria1.andUserIdEqualTo(allAddress.getUserId());
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(orderExample);
        for (MarketOrder order : marketOrders) {
            checkOut.setActualPrice(order.getActualPrice());//实付费用=orderPrice-integral_price
            checkOut.setCouponPrice(order.getCouponPrice());//优惠券减免
            checkOut.setFreightPrice(order.getFreightPrice());//运费
            checkOut.setGoodsTotalPrice(order.getGoodsPrice());//商品总费用
            checkOut.setGrouponPrice(order.getGrouponPrice());//团购优惠0
            checkOut.setOrderTotalPrice(order.getOrderPrice());//订单费用， = goods_price + freight_price - coupon_price
        }

        //判断可用优惠券的数量
        //先查询coupon-user表
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria2 = couponUserExample.createCriteria();
        criteria2.andUserIdEqualTo(allAddress.getUserId());
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(couponUserExample);

        int a = 0;
        for (MarketCouponUser couponUser : marketCouponUsers) {
            //判断是否有可用优惠券
            if (couponUser.getStatus() == 0) {
                //未使用再判断是否在有效日期内，如果是则可用优惠券加一
                if (new Date().getTime() >= couponUser.getStartTime().getTime()
                        && new Date().getTime() <= couponUser.getEndTime().getTime()) {
                    a++;
                }
            }
            checkOut.setAvailableCouponLength(a);
        }

        return checkOut;
    }
}

